﻿using System;
using System.Collections.Generic;
using System.Linq;
using BKO.DataAccesss;
using BKO.DataAccesss.Repositories;
using BKO.Domain.Model;
using BKO.Domain.Services;
using BKO.Domain.Repositories;

namespace BKO.Services
{
	public class UnitService : IUnitService
	{
		private readonly IRepository<IUnit> _repository;
		
		public UnitService(string connectionString)
		{
			_repository = new UnitRepository(BKODataContextSingletone.GetInstance(connectionString));
		}

		public IUnit Get(int id)
		{
			return _repository.GetAll().SingleOrDefault<IUnit>(m => m.ID == id);
		}

		public List<IUnit> GetByType(string type)
		{
			return _repository.GetAll().Where(u => u.SPR_Type == type).ToList();
		}

		public List<IUnit> GetAll()
		{
			return _repository.GetAll().ToList<IUnit>();
		}

		public IUnit Add(string invNo, string sn, int sprId, string sprType, int kabId, decimal price)
		{
			IUnit entity = _repository.CreateEmpty();
			entity.INV_NO = invNo;
			entity.SN = sn;
			entity.SPR_ID = sprId;
			entity.SPR_Type = sprType;
			entity.CabinetId = kabId;
			entity.Price = price;
			_repository.Add(entity);
			return entity;
		}

		public void Update(int id, string invNo, string sn, int sprId, string sprType, int kabId, decimal price)
		{
			IUnit entity = Get(id);
			entity.INV_NO = invNo;
			entity.SN = sn;
			entity.SPR_ID = sprId;
			entity.SPR_Type = sprType;
			entity.CabinetId = kabId;
			entity.Price = price;
			_repository.Update();
		}

		public void Delete(int id)
		{
			_repository.Delete(Get(id));
		}
	}
}
